package com.example.wj.controller;

import com.example.wj.pojo.Book;
import com.example.wj.pojo.Result;
import com.example.wj.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class LibraryController {
    @Autowired
    BookService bookService;

    /*
     * 查看书本路径
     * */
    @GetMapping("/api/books")
    public List<Book> list() throws Exception {
        return bookService.list();
    }

    /*
     * 添加或更新书本路径
     * */
    @PostMapping("/api/books")
    public void addOrUpdate(@RequestBody Book book) throws Exception {

        int save = bookService.save(book);
        System.out.println("成功添加" + save + "书本");

    }

    /*
     * 删除书本路径
     * */
    @PostMapping("/api/delete")
    public void delete(@RequestBody Book book) throws Exception {
        bookService.delete(book.getId());
    }

    @PostMapping("/api/subcover")
    public void reface(@RequestParam("newcover") String newcover, @RequestParam("id") int id) throws Exception {
        Book byId = bookService.findById(id);
        byId.setCover(newcover);
        bookService.save(byId);
    }

    /*
     *
     * 按照类型查看书本路径
     * */
    @RequestMapping("/api/categories/books")
    public List<Book> listbycategroy(@RequestParam("cid") int cid) throws Exception {
        System.out.println(cid);
        if (cid == 0) {
            return list();
        } else {
            return bookService.listbycategroy(cid);
        }
    }

    @GetMapping("/api/author/{name}")
    public List<Book> findByAuthor(@PathVariable String name) {
        List<Book> byAuthor = bookService.findByAuthor(name);
        return byAuthor;
    }

    @GetMapping("/api/search")
    public Book[] findByTitle(@RequestParam String keyword) {
        Book byTitle = bookService.findByTitle(keyword);
        Book[] books = new Book[]{byTitle};
        return books;
    }



}
